package com.choichumgming.rentcat.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.choichumgming.rentcat.dto.OssCallbackResult;
import com.choichumgming.rentcat.dto.OssPolicyResult;
import com.choichumgming.rentcat.service.OssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Service
public class OssServiceImpl implements OssService {
    private String ALIYUN_OSS_BUCKET_NAME = "rentcatapp";

    private String ALIYUN_OSS_ENDPOINT = "sts.cn-shanghai.aliyuncs.com";

    private String accessKeyId = "LTAI4FswDF3ziLGmxQW3URN7";

    private String accessKeySecret = "aGx2nEU0AwOAUOyB3bwuX5cBRZpsid";

    private String roleArn = "acs:ram::1915945265606685:role/test";

    private String roleSessionName = "session-name";
    private String policy = null;


    /**
     * 签名生成
     */
    @Override
    public OssPolicyResult policy() {
        OssPolicyResult result = new OssPolicyResult();
        try {
            // 添加endpoint（直接使用STS endpoint，前两个参数留空，无需添加region ID）
            DefaultProfile.addEndpoint("", "", "Sts", ALIYUN_OSS_ENDPOINT);
            // 构造default profile（参数留空，无需添加region ID）
            IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
            // 用profile构造client
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setMethod(MethodType.POST);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(policy); // 若policy为空，则用户将获得该角色下所有权限
            request.setDurationSeconds(1000L); // 设置凭证有效时间
            final AssumeRoleResponse response = client.getAcsResponse(request);
            result.setAccessKeyId(response.getCredentials().getAccessKeyId());
            result.setAccessKeySecret(response.getCredentials().getAccessKeySecret());
            result.setSecurityToken(response.getCredentials().getSecurityToken());
            log.info("Expiration: " + response.getCredentials().getExpiration());
            log.info("Access Key Id: " + response.getCredentials().getAccessKeyId());
            log.info("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
            log.info("Security Token: " + response.getCredentials().getSecurityToken());
            log.info("RequestId: " + response.getRequestId());
        } catch (ClientException e) {
            log.info("Failed：");
            log.info("Error code: " + e.getErrCode());
            log.info("Error message: " + e.getErrMsg());
            log.info("RequestId: " + e.getRequestId());
        }
        return result;
    }

    @Override
    public OssCallbackResult callback(HttpServletRequest request) {
        OssCallbackResult result= new OssCallbackResult();
        String filename = request.getParameter("filename");
        filename = "http://".concat(ALIYUN_OSS_BUCKET_NAME).concat(".").concat(ALIYUN_OSS_ENDPOINT).concat("/").concat(filename);
        result.setFilename(filename);
        result.setSize(request.getParameter("size"));
        result.setMimeType(request.getParameter("mimeType"));
        result.setWidth(request.getParameter("width"));
        result.setHeight(request.getParameter("height"));
        return result;
    }
}
